<template>
  <div class="container">
    <div class="app-container">
      <!-- 角色管理内容 -->
      <div class="role-operate">
        <el-button size="mini" type="primary" @click="showDialog = true">添加角色</el-button>
      </div>
      <!-- 放置table组件 -->
      <el-table :data="roleList">
        <!-- 放置列 -->
        <el-table-column prop="name" align="center" width="200" label="角色" >
          <!-- 作用域插槽 -->
          <template v-slot="{ row }">
            <el-input size="mini" v-if="row?.isEdit" v-model="row.editRole.name" />
            <span v-else>{{ row.name }}</span>
          </template>

        </el-table-column>
        <el-table-column prop="state" align="center" width="200" label="启用">
          <!-- 自定义结构 -->
          <!-- v-slot 可以获取所在插槽父组件的一行数据 -->
          <template v-slot="{row}">
            <el-switch v-if="row.isEdit" :active-value="1"
    :inactive-value="0" v-model="row.editRole.state"></el-switch>
            <span v-else>{{ row.state === 1 ? "已启用"  : '未启用' }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="description" align="center" label="描述" >
          <template v-slot="{ row }">
            <el-input size="mini" v-if="row.isEdit" v-model="row.editRole.description" type="textarea"></el-input>
            <span v-else>{{ row.description }}</span>
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" >
          <!-- 自定义结构 -->
          <template v-slot="{ row }">
           <template v-if="row.isEdit">
             <el-button size="mini" type="primary" @click="editConfirm(row)">确认</el-button>
             <el-button size="mini" @click="editCancel(row)" >取消</el-button>
            </template>

           <template v-else>
            <el-button type="text" size="mini" @click="btnPer(row.id)">分配权限</el-button>
            <el-button type="text" size="mini" @click="editChange(row)">编辑</el-button>
            <el-popconfirm
              title="这是一段内容确定删除吗？"
              @onConfirm="confirmDel(row.id)"
            >
            <el-button type="text" size="mini" slot="reference" style="margin-left: 10px;">删除</el-button>
          </el-popconfirm>


           </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 放置分页组件 -->
      <el-row type="flex" style="height:60px" align="middle" justify="end">
        <!-- 放置分页组件 -->
        <el-pagination 
        :page-size="pageParams.pagesize"
        :current-page="pageParams.page"
        :total="pageParams.total"
        background  layout="prev, pager, next"
        @current-change="changePage"
        ></el-pagination >
      </el-row>
    </div>
    <el-dialog @close="cancel" title="添加角色" :visible.sync="showDialog" style="width: 1000px; margin: 0 auto;">
      <el-form ref="roleForm" :rules="roleRules" class="form" label-width="100px" :model="roleForm">
        <el-form-item label="角色名称" prop="name">
          <el-input style="width: 300px;" size="mini" v-model="roleForm.name"></el-input>
        </el-form-item>
        <el-form-item label="启用" prop="state">
          <el-switch v-model="roleForm.state" size="mini"   :active-value="1"
    :inactive-value="0" />
        </el-form-item>
        <el-form-item label="角色描述" prop="description">
          <el-input style="width: 300px;" size="mini" type="textarea" v-model="roleForm.description"></el-input>
        </el-form-item>
        <el-form-item id="btn" >
          <el-button type="primary" @click="confirm">确定</el-button>
          <el-button @click="cancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-dialog title="分配权限" :visible.sync="showPerDialog">
      <el-tree ref="formTree" check-strictly node-key="id" :default-checked-keys="permIds" :data="permissionList" :props="{ label: 'name'}" default-expand-all :show-checkbox="true"
      ></el-tree>
      <el-row type="flex" justify="center" slot="footer" >
        <el-button  size="mini" type="primary" @click="btnSubmit">确定</el-button>
        <el-button size="mini" @click="cancel">取消</el-button>
      </el-row>
    </el-dialog>
  </div>
</template>
<script>
import { getRoleList,  addRole, editRole,setRoleAuth, delRole , getRoleDetail} from '@/api/role'
import { getPermissionList } from '@/api/permission'
import { transListToTree} from '@/utils/index.js'
export default {
  data() {
    return {
      roleList: [],
      // 分页信息
      pageParams: {
        page: 1, // 当前页码
        pagesize: 5 ,// 每页显示多少条
        total: 0
      },
      // 弹层是否显示
      showDialog: false,
      roleForm: {
        name: '',
        description: '',
        state: 0 // 默认未1启用 关闭 0 打开1
      },
      roleRules: {
        name: [
          {
              required: true,
              message: '请输入角色名称',
              trriger: 'blur'
          }
        ],
        description: [
          {
            required: true,
            message: '请输入角色描述',
            trriger: 'blur'
          }
        ]
      },
      showPerDialog: false,
      permissionList: [],
      permIds: [],
      currentRoleId: ''

    }
  },
methods: {  
  async getRoleData() {
    const res = await getRoleList(this.pageParams)
    // console.log(res);
    this.roleList = res.rows
    this.pageParams.total = res.total

    // 为每个数据对方添加一个响应式数据isEdit来控制是否处于编辑转态
    this.roleList.forEach(item => {
      // 添加的状态在后期需要修改，因此在这里使用this.$set()方法来添加一个响应式数据
      this.$set(item, 'isEdit', false)
      // 定义拷贝一份数据对象用于编辑时缓存
      this.$set(item, 'editRole', {
        name: item.name,
        description: item.description,
        state: item.state
      })
    })
    console.log(this.roleList);

  },
  
  // 分页改变的时候触发
  changePage(newPage) {
    // console.log(newPage);
    this.pageParams.page = newPage
    this.getRoleData()
  },
  // 弹层取消
  cancel() {
    this.showDialog = false
    this.$refs.roleForm.resetFields()
  },
  // 弹层确认
  confirm() {
    this.$refs.roleForm.validate(  async valid => {
      // 判断表单是否通过校验
      if (valid) {
        // console.log(this.roleForm);
        const res = await addRole(this.roleForm)
        // console.log(res);
        this.$refs.roleForm.resetFields()
        this.showDialog = false
        this.$message.success('添加成功')
        this.getRoleData()
      }
    } )
  },

  // 行内编辑
  editChange(row) {
    row.isEdit = true
    row.editRole.name = row.name
    row.editRole.description = row.description
    row.editRole.state = row.state
  },
  
  // 行内编辑取消
  editCancel(row) {
    row.isEdit = false

  },

  // 行内编辑确定
   async editConfirm(row) {
    if (row.editRole.name && row.editRole.description) {
      console.log(row);
      await editRole({...row.editRole, id: row.id})
      row.name = row.editRole.name
      row.description = row.editRole.description
      row.state = row.editRole.state
      // console.log(res);
      this.$message.success('修改成功')
      this.editCancel(row)
    }
    else{
      this.$message.warning('角色名和描述不能为空')
    }
  
  }
  ,
  // 删除提示框确定逻辑
  async confirmDel(id) {
    // 调用接接口删除数据
   await delRole(id)
  //  判断当前删除数据是否为每页最后一条数据，如果是，则删除后需要渲染前一页数据
  if (this.roleList.length === 1) this.pageParams.page--
  // 提示用户
  this.$message.success('删除成功')
  // 重新渲染页面
  this.getRoleData()
  },
  cancel() {
    this.showPerDialog = false
  },

  // 分配权限
  async btnPer(id) {
    const res = transListToTree(await getPermissionList(), 0)
    console.log(res);
    this.permissionList = res
    this.currentRoleId = id
    const { permIds} = await getRoleDetail(id)
    this.permIds = permIds
    console.log(permIds);
    this.showPerDialog  = true

  },
  // 权限分配确认
  async btnSubmit() {
    const permIdsList = this.$refs.formTree.getCheckedKeys()
    const res = await setRoleAuth({
      id: this.currentRoleId,
      permIds: permIdsList
    })
    // console.log(this.currentRoleId, permIdsList);
    this.$message.success('权限分配成功')
    this.showPerDialog = false
  }
},

created() {
  this.getRoleData()
}
}

</script>

<style scoped>
.role-operate {
  padding: 10px;
}
.form {
  text-align: left;
}
#btn {
  display: flex;
  justify-content: center;
  padding-right: 100px;
}
</style>